package 栈;

import java.util.Deque;

public class 数组实现环形队列 {
    //队列的最后一个元素不存放数字
    private int[] loopQueue = new int[6];
    int head = 0;
    int tail = 0;

    public void  offer(int val){
        if (isFull()){
            throw new IndexOutOfBoundsException("Array is full,not to append");
        }
        loopQueue[tail] = val;
        tail = (tail + 1) % loopQueue.length;
    }

    public int poll(){
        if (isEmpty()){
            throw  new NullPointerException("Array is empty,not to delete");
        }
        int val = loopQueue[head];
        head = (head + 1) % loopQueue.length;
        return val;
    }

    public int peek(){
        if (isEmpty()){
            throw new NullPointerException("Arrat is empty,not to delete");
        }
        return loopQueue[head];
    }

    //队列空
    public boolean isEmpty(){
        return head == tail;
    }

    //队列满
    public boolean isFull(){
        return (tail + 1) % loopQueue.length == head;
    }

    @Override
    public String toString(){
        StringBuilder sb = new StringBuilder();
        sb.append("head [");
        int lastIndex = tail == 0 ? loopQueue.length - 1 : tail - 1;
        for (int i = head; i != tail; i = (i + 1) % loopQueue.length){
            sb.append(loopQueue[i]);

            if (i != lastIndex){
                sb.append(",");
            }
        }
        sb.append("] tail");
        return sb.toString();
    }
}

class TestLoopQueue{
    public static void main(String[] args) {
        数组实现环形队列 o = new 数组实现环形队列();
        o.offer(1);
        o.offer(2);
        o.offer(3);
        o.offer(4);
        System.out.println(o.toString());
        o.poll();
        System.out.println(o.toString());
        System.out.println(o.peek());
    }
}
